﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Xml.Linq;
using SmartSpace.Core;
using SmartSpace.Data;
using SmartSpace.Workflow;

namespace SsTool
{
    /// <summary>
    /// Interaction logic for InstallPage.xaml
    /// </summary>
    public partial class InstallPage : Page
    {
        public InstallPage()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            IInstallService installService = App.Get<IInstallService>();
            if (installService.InstallDatabase())
            {
                ImportDatas();
                MessageBox.Show("安装成功!");
            }
            else
            {
                MessageBox.Show("安装失败!");
            }
        }

        private void ImportDatas()
        {
            ICoreService coreService = App.Get<ICoreService>();
            IDataService dataService = App.Get<IDataService>();

            _ctlBtnImportUser_Click(null, null);

            XDocument xTypeMetadataDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "./Datas/typemetadata.xml");
            foreach (XElement element in xTypeMetadataDoc.Root.Elements("item"))
            {
                TypeMetadata type1 = new TypeMetadata();
                type1.Id = new Guid(element.Attribute("id").Value);
                type1.Name = element.Attribute("name").Value;
                type1.IsSystem = Convert.ToBoolean(element.Attribute("is-system").Value);
                type1.IsComplex = Convert.ToBoolean(element.Attribute("is-complex").Value);
                type1.Caption = element.Attribute("caption").Value;
                type1.DbType = element.Attribute("db-type").Value;
                type1.MinLength = Convert.ToInt32(element.Attribute("min-length").Value);
                type1.MaxLength = Convert.ToInt32(element.Attribute("max-length").Value);
                dataService.StoreType(type1);
            }

            //string[] parserArray = new string[]{
            //    // id, typeid,name,caption
            //    "{647EBFA9-A149-46F5-93C0-79B45302DE85},{E4177A77-3BF8-4EB9-ADF5-1730E5879F43},~/Controls/SsDateControl.ascx,日期控件",
            //    "{F5C490F3-3C56-443C-9273-C009C626D54C},{A052F415-AF8B-4BB6-9C2B-0F8F4425888F},~/Controls/SsTimeControl.ascx,时间控件",
            //    "{CCFDC8B6-073A-47DC-B7F1-7AE4059F5F95},{83AEF0ED-CC1E-487B-8418-DBBE1276B5AF},~/Controls/SsOperatorControl.ascx,操作用户控件"
            //};
            //for (int parserIndex = 0; parserIndex < parserArray.Length; parserIndex++)
            //{
            //    string[] items = parserArray[parserIndex].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            //    TypeUIParser parser = new TypeUIParser();
            //    parser.Id = new Guid(items[0]);
            //    parser.TypeId = new Guid(items[1]);
            //    parser.Name = items[2];
            //    parser.Caption = items[3];
            //    service.StoreParser(parser);
            //}

            EntityMetadata entity1 = new EntityMetadata();
            entity1.Id = Guid.NewGuid();
            entity1.Name = "Entity1";
            entity1.Caption = "测试实体1";
            entity1.Properties = new List<SmartSpace.Data.PropertyMetadata>();

            string[] pros = new string[] { 
                "__Id,标识,{1722EECC-FCB0-4FF9-9F47-DD8EF67AD3E2},true,true", 
                "__Name,名称,{6C89BE2E-2EC5-46CD-9E6C-BE6E50438007},false,true", 
                "__Creator,创建人,{83AEF0ED-CC1E-487B-8418-DBBE1276B5AF},false,true", 
                "__CreatedDate,创建时间,{FD8D0D23-8A82-4EE8-80C1-5BA44467B2CE},false,true", 
                "Txt1,文本信息1,{6C89BE2E-2EC5-46CD-9E6C-BE6E50438007},false,false", 
                "Txt2,文本信息2,{6C89BE2E-2EC5-46CD-9E6C-BE6E50438007},false,false", 
                "Txt3,大文本信息3,{7465F85A-F88A-41BF-8F81-3F2C20458AF8},false,false", 
                "Time1,时间字段,{A052F415-AF8B-4BB6-9C2B-0F8F4425888F},false,false", 
                "Date1,日期字段,{E4177A77-3BF8-4EB9-ADF5-1730E5879F43},false,false", 
                "Creator1,创建人字段,{83AEF0ED-CC1E-487B-8418-DBBE1276B5AF},false,false"};
            for (int index = 0; index < pros.Length; index++)
            {
                string[] items = pros[index].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                SmartSpace.Data.PropertyMetadata pro1 = new SmartSpace.Data.PropertyMetadata();
                pro1.Id = Guid.NewGuid();
                pro1.IsIdentity = Convert.ToBoolean(items[3]);
                if (pro1.IsIdentity)
                {
                    // 标识字段不能为空
                    pro1.IsNullable = false;
                }
                else
                {
                    pro1.IsNullable = true;
                }
                pro1.Name = items[0];
                pro1.Caption = items[1];
                pro1.IsSystem = Convert.ToBoolean(items[4]);
                pro1.EntityId = entity1.Id;
                TypeMetadata type = dataService.FindType(new Guid(items[2]));
                pro1.Type = type;
                pro1.TypeId = type.Id;
                pro1.MaxLength = type.MaxLength;
                pro1.MinLength = type.MinLength;
                pro1.OrderIndex = index;
                entity1.Properties.Add(pro1);
            }

            dataService.StoreEntity(entity1);

            _ctlBtnImportModuleData_Click(null, null);
            _ctlBtnImportEventType_Click(null, null);
            _ctlBtnImportDictionary_Click(null, null);
            _ctlBtnImportOrg_Click(null, null);
            _ctlBtnImportOrgMember_Click(null, null);
            _ctlBtnImportTheme_Click(null, null);
        }

        private void _ctlBtnImportModuleData_Click(object sender, RoutedEventArgs e)
        {
            ICoreService coreService = App.Get<ICoreService>();
            //PagedList<Module> existModules = coreService.GetModules(0, 999);
            //foreach (var item in existModules)
            //{
                
            //}

            //SmartSpace.Core.Module module1 = new SmartSpace.Core.Module();
            //module1.Id = Guid.NewGuid();
            //module1.Name = "Workflow-Web-Module";
            //module1.Caption = "Web流程模块";
            //module1.Views = new List<SmartSpace.Core.ModuleView>();

            //SmartSpace.Core.ModuleView view1 = new SmartSpace.Core.ModuleView();
            //view1.Id = Guid.NewGuid();
            //view1.Name = "./workflow/ListTemplate.aspx";
            //view1.Caption = "列表数据模版";
            //module1.Views.Add(view1);

            //SmartSpace.Core.ModuleView view2 = new SmartSpace.Core.ModuleView();
            //view2.Id = Guid.NewGuid();
            //view2.Name = "./workflow/CreateTemplate.aspx";
            //view2.Caption = "创建数据模版";
            //module1.Views.Add(view2);
            //coreService.SaveModule(module1);

            //SmartSpace.Core.Module module2 = new SmartSpace.Core.Module();
            //module2.Id = Guid.NewGuid();
            //module2.Name = "Workflow-WinForm-Module";
            //module2.Caption = "WinForm流程模块";
            //module2.Views = new List<SmartSpace.Core.ModuleView>();
            //SmartSpace.Core.ModuleView view2_1 = new SmartSpace.Core.ModuleView();
            //view2_1.Id = Guid.NewGuid();
            //view2_1.Name = "SmartSpace.Shell.Views.WfListTemplate";
            //view2_1.Caption = "列表数据模版";
            //module2.Views.Add(view2_1);
            //coreService.SaveModule(module2);

            XDocument xDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "./Datas/module.xml");
            foreach (XElement moduleElement in xDoc.Root.Elements("module"))
            {
                SmartSpace.Core.Module module3 = new SmartSpace.Core.Module();
                module3.Id = new Guid(moduleElement.Attribute("id").Value);
                module3.Package = moduleElement.Attribute("package").Value;
                module3.Name = moduleElement.Attribute("name").Value;
                module3.Caption = moduleElement.Attribute("caption").Value;
                module3.Views = new List<SmartSpace.Core.ModuleView>();

                foreach (XElement viewElement in moduleElement.Elements("view"))
                {
                    SmartSpace.Core.ModuleView view3_1 = new SmartSpace.Core.ModuleView();
                    view3_1.Id = new Guid(viewElement.Attribute("id").Value);
                    view3_1.Name = viewElement.Attribute("name").Value;
                    view3_1.Caption = viewElement.Attribute("caption").Value;
                    module3.Views.Add(view3_1);
                }
                coreService.SaveModule(module3);
            }
        }

        private void _ctlBtnImportEventType_Click(object sender, RoutedEventArgs e)
        {
            IWorkflowService dataService = App.Get<IWorkflowService>();
            XDocument xDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "./Datas/eventtype.xml");
            foreach (XElement moduleElement in xDoc.Root.Elements("item"))
            {
                SmartSpace.Workflow.EventType type = new SmartSpace.Workflow.EventType();
                type.Id = new Guid(moduleElement.Attribute("id").Value);
                type.Name = moduleElement.Attribute("name").Value;
                type.Caption = moduleElement.Attribute("caption").Value;
                dataService.StoreEventType(type);
            }
        }

        private void _ctlBtnImportDictionary_Click(object sender, RoutedEventArgs e)
        {
            IDataService dataService = App.Get<IDataService>();
            XDocument xDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "./Datas/dictionary.xml");
            foreach (XElement moduleElement in xDoc.Root.Elements("type"))
            {
                SmartSpace.Data.DictionaryType type = new SmartSpace.Data.DictionaryType();
                type.Id = new Guid(moduleElement.Attribute("id").Value);
                type.Caption = moduleElement.Attribute("caption").Value;
                type.OrderIndex = Convert.ToInt32(moduleElement.Attribute("orderindex").Value);
                type.Datas = new List<DictionaryData>();

                IEnumerable<XElement> itemElements = moduleElement.Elements("item");
                foreach (XElement itemElement in itemElements)
                {
                    DictionaryData data = new DictionaryData();
                    data.Id = new Guid(itemElement.Attribute("id").Value);
                    data.Code = itemElement.Attribute("code").Value;
                    data.Caption = itemElement.Attribute("caption").Value;
                    data.OrderIndex = Convert.ToInt32(moduleElement.Attribute("orderindex").Value);
                    data.Type = type;
                    data.TypeId = type.Id;

                    type.Datas.Add(data);
                }

                dataService.SaveDictionaryType(type);
            }
        }

        private void _ctlBtnImportOrg_Click(object sender, RoutedEventArgs e)
        {
            ICoreService coreService = App.Get<ICoreService>();
            XDocument xDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "./Datas/org.xml");
            Stack<XElement> roots = new Stack<XElement>();
            foreach (XElement moduleElement in xDoc.Root.Elements("org"))
            {
                roots.Push(moduleElement);

                SmartSpace.Core.Org org = new SmartSpace.Core.Org();
                org.Id = new Guid(moduleElement.Attribute("id").Value);
                org.Caption = moduleElement.Attribute("caption").Value;
                org.Code = moduleElement.Attribute("code").Value;
                org.Type = Convert.ToInt32(moduleElement.Attribute("type").Value);
                org.SortIndex = Convert.ToInt32(moduleElement.Attribute("orderindex").Value);
                org.Children = new List<SmartSpace.Core.Org>();
                coreService.SaveOrg(org);
            }

            while (roots.Count > 0)
            {
                XElement root = roots.Pop();
                foreach (XElement orgElement in root.Elements("org"))
                {
                    roots.Push(orgElement);

                    SmartSpace.Core.Org org = new SmartSpace.Core.Org();
                    org.ParentId = new Guid(root.Attribute("id").Value);
                    org.Id = new Guid(orgElement.Attribute("id").Value);
                    org.Caption = orgElement.Attribute("caption").Value;
                    org.Code = orgElement.Attribute("code").Value;
                    org.Type = Convert.ToInt32(orgElement.Attribute("type").Value);
                    org.SortIndex = Convert.ToInt32(orgElement.Attribute("orderindex").Value);
                    org.Children = new List<SmartSpace.Core.Org>();
                    coreService.SaveOrg(org);

                    roots.Push(orgElement);
                }
            }
        }

        private void _ctlBtnImportOrgMember_Click(object sender, RoutedEventArgs e)
        {
            ICoreService coreService = App.Get<ICoreService>();
            XDocument xDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "./Datas/orgmember.xml");
            
            foreach (XElement orgElement in xDoc.Root.Elements("org"))
            {
                foreach (XElement userElement in orgElement.Elements("user"))
                {
                    Guid orgId = new Guid(orgElement.Attribute("id").Value);
                    Guid userId = new Guid(userElement.Attribute("id").Value);
                    bool isMajor = Convert.ToBoolean(userElement.Attribute("is-major").Value);
                    Org org = coreService.GetOrg(orgId);
                    User user = coreService.GetUser(userId);

                    coreService.AddMember(org, user, isMajor);
                }
            }
        }

        private void _ctlBtnImportUser_Click(object sender, RoutedEventArgs e)
        {
            ICoreService coreService = App.Get<ICoreService>();

            string[] roleArray = new string[]{
                "{390ECB9D-3D20-456B-BE09-5A200FE26E51},role-user,普通用户",
                "{9F612CD0-27E7-420A-9685-BA9A3B1E99C5},role-chuzhang,处长"
            };

            for (int roleIndex = 0; roleIndex < roleArray.Length; roleIndex++)
            {
                string[] items = roleArray[roleIndex].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                Role role = new Role();
                role.Id = new Guid(items[0]);
                role.Name = items[1];
                role.Caption = items[2];
                role.CreatedTime = DateTime.Now;
                coreService.StoreRole(role);
            }

            XDocument xUserDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "./Datas/user.xml");
            foreach (XElement element in xUserDoc.Root.Elements("item"))
            {
                User user = new User();
                user.Id = new Guid(element.Attribute("id").Value);
                user.Name = element.Attribute("caption").Value;
                user.Telphone = element.Attribute("telphone").Value;
                user.Account = element.Attribute("account").Value;
                user.CreatedTime = DateTime.Now;
                user.Email = element.Attribute("email").Value;
                coreService.StoreUser(user);
            }
        }

        private void _ctlBtnImportTheme_Click(object sender, RoutedEventArgs e)
        {
            ICoreService coreService = App.Get<ICoreService>();

            XDocument xUserDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "./Datas/theme.xml");
            foreach (XElement element in xUserDoc.Root.Elements("theme"))
            {
                Theme theme = new Theme();
                theme.Id = new Guid(element.Attribute("id").Value);
                theme.Caption = element.Attribute("caption").Value;
                theme.Name = element.Attribute("name").Value;
                theme.Package = element.Attribute("package").Value;
                theme.PreviewImageUrl = element.Attribute("previewimageurl").Value;
                coreService.SaveTheme(theme);
            }
        }
    }
}
